package org.simple.web.jwt.filter;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.simple.web.jwt.service.AuthenticationService;
import org.simple.web.jwt.service.JwtService;
import org.simple.web.jwt.service.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;

/**
 * 项目名称：simple-framework
 * 类名称：UserRefreshFilter
 * 类描述：UserRefreshFilter
 * 创建时间：2018/11/27
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
public class UserRefreshFilter extends AbstractAuthenticationProcessingFilter {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private RequestService requestService;

    public UserRefreshFilter(AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher("/auth/refresh"));
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String token = requestService.getToken(request);
        if (jwtService.validateRefreshToken(token)) {
            String subject = jwtService.getSubjectFromToken(token);
            return authenticationService.loadAuthenticationByName(subject);
        }
        return null;
    }


}

